#include<iostream>
#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>


using namespace std;

int main()
{
    // 创建匿名管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    // 判段是否创建成功
    assert(n != -1);
    (void)n;

    // 父进程写，子进程读
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork()");
        exit(1);
    }
    else if(id == 0)
    {
        // 关系写端
        close(pipefd[1]);
        // 缓冲区放数据
        char buff[1024 * 8];
        // read 读取数据
        while(true)
        {
            ssize_t s = read(pipefd[0], buff, sizeof(buff) - 1);
            // 判断是否可以继续读
            // 1. 写端没有关闭
            if(s > 0)
            {
                buff[s] = 0;
                cout<<"子进程获取的内容: " << buff << endl;
            }
            // 2. 写端关闭
            else if(s == 0)
            {
                cout<<"写端关闭，子进程退出！" << endl;
                break;
            }
        }
        exit(2);
    }
    else 
    {
        // 父进程写
        // 关闭读端
        close(pipefd[0]);
        // 写入的内容
        char send_buff[] = "I am father";
        // char* send_buff = "I am father";
        // char send_buff[1024*4];
        int count = 0;
        while(true)
        {
            // sprintf(send_buff, "%s", meg);
            // 写入
            write(pipefd[1], send_buff, sizeof(send_buff));
            sleep(1);
            cout<<"父进程在写 " << count++ << endl;
            if(count == 5) break; 
        }
        close(pipefd[1]);
        pid_t ret = waitpid(id, nullptr, 0); // 阻塞等待
        assert(ret != -1); // 等待成功
        (void)ret;
    }

    return 0;
}